using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Wicresoft.OmsClient.OmsService;

namespace Wicresoft.OmsClient
{
    class ContactsSync
    {
        private Thread conSync;

        public ContactsSync()
        {
            conSync = new Thread(new ThreadStart(Main));
        }

        public void StartService()
        {
            if (conSync == null)
                conSync = new Thread(new ThreadStart(Main));
            conSync.Start();
        }

        public void StopService()
        {
            conSync.Abort();
        }

        private static void Main()
        {
            OMSService oms = new OMSService();
            while (true)
            {
                int syncinterval = SyncConfigManage.SyncInterval * 1000;
                try
                {
                    if (SyncConfigManage.EnableContactSync.ToLower() != "true" || !UserService.IsAuthorized)
                    {
                        Thread.Sleep(syncinterval);
                        continue;
                    }
                    string url = SyncConfigManage.ProviderUrl;
                    string email = SyncConfigManage.Email;
                    if (url == "" || email == "")
                    {                        
                        Thread.Sleep(syncinterval);
                        continue;
                    }

                    Logger.Debug("Start Contacts Sync");
                    oms.Url = url;
                    string xml = oms.GetContacts(email, "any");
                    ContactsService.CompareContacts(xml);
                    Logger.Debug("End Contacts Sync");

                }
                catch (Exception ex)
                {                   
                    Logger.Exception("contact sync thread Main Exception", ex);
                }

                Thread.Sleep(syncinterval);
            }
        }
    }
}
